package com.barneyx.mshinfoplatform.util;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.barneyx.mshinfoplatform.entity.area.AreaEntity;
import com.barneyx.mshinfoplatform.entity.common.DefaultSettingConfig;
import com.barneyx.mshinfoplatform.entity.info.InfoSettingEntity;
import com.barneyx.mshinfoplatform.exception.MshException;
import com.barneyx.mshinfoplatform.service.admin.IAreaAdminUserMapEntityService;
import com.barneyx.mshinfoplatform.service.area.IAreaEntityService;
import com.barneyx.mshinfoplatform.service.info.IInfoSettingEntityService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

import static com.barneyx.mshinfoplatform.common.ExResult.ResponseCode.AREA_NULL;

@Component
public class AreaUtil {

    @Resource
    private IAreaEntityService areaService;

    @Resource
    private IInfoSettingEntityService infoSettingService;

    @Resource
    private DefaultConfigUtil defaultConfigUtil;


    public AreaEntity getDefaultAreaInfo() {
        return areaService.getOne(new LambdaQueryWrapper<AreaEntity>().eq(AreaEntity::getAreaDefault, true));
    }

    public List<AreaEntity> getAreaListByIds(List<String> ids) {
        return areaService.list(new LambdaQueryWrapper<AreaEntity>()
                .in(AreaEntity::getAreaId, ids));
    }

    /**
     * 获取请求者的所属地区编号
     *
     * @return
     * @throws MshException
     */
    public String getCurrentAreaId() throws MshException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String area_id = request.getHeader("areaid");
        if (StrUtil.isBlank(area_id)) area_id = request.getParameter("areaid");
        if (StrUtil.isBlank(area_id)) area_id = getDefaultAreaInfo().getAreaId();
        return area_id;
    }


    /**
     * 创建子区域,带初始化设置信息
     *
     * @param area
     * @param child
     * @return
     */
    @Transactional
    public boolean createArea(AreaEntity area, boolean child) {
        boolean save = areaService.save(area);
        if (save && child) {
            List<DefaultSettingConfig> info_area_settings = defaultConfigUtil.getDefaultConfigByType("INFO_AREA_SETTINGS");
            List<InfoSettingEntity> InfoSettingsList = new ArrayList<>();

            info_area_settings.forEach(s -> {
                InfoSettingEntity setting = new InfoSettingEntity();
                setting.setAreaId(area.getAreaId());
                setting.setInfoSettingCode(s.getConfigKey());
                setting.setInfoSettingValue(s.getConfigValue());
                setting.setInfoSettingRemark(s.getConfigRemark());
                setting.setInfoSettingName(s.getConfigName());
                setting.setInfoSettingContent(s.getConfigContent());
                InfoSettingsList.add(setting);
            });
            return infoSettingService.saveBatch(InfoSettingsList);
        }
        return save;
    }

    /**
     * 检查区域设置，未配置选项
     */
    public void CheckInfoSetting() {
        List<DefaultSettingConfig> info_area_settings = defaultConfigUtil.getDefaultConfigByType("INFO_AREA_SETTINGS");
        List<AreaEntity> area_list = areaService.list(new LambdaQueryWrapper<AreaEntity>().ne(AreaEntity::getAreaParentId, "0"));
        List<InfoSettingEntity> insert_list = new ArrayList<>();

        info_area_settings.forEach(setting -> {
            area_list.forEach(area -> {
                long count = infoSettingService.count(new LambdaQueryWrapper<InfoSettingEntity>().eq(InfoSettingEntity::getInfoSettingCode, setting.getConfigKey()));
                if (count == 0) {
                    InfoSettingEntity infoSetting = new InfoSettingEntity();
                    infoSetting.setAreaId(area.getAreaId());
                    infoSetting.setInfoSettingCode(setting.getConfigKey());
                    infoSetting.setInfoSettingName(setting.getConfigName());
                    infoSetting.setInfoSettingRemark(setting.getConfigRemark());
                    infoSetting.setInfoSettingValue(setting.getConfigValue());
                    infoSetting.setInfoSettingContent(setting.getConfigContent());

                    insert_list.add(infoSetting);

                }
            });
        });
        infoSettingService.saveBatch(insert_list);

    }


    /**
     * 修改地区信息
     *
     * @param area
     * @return
     */
    public boolean updateArea(AreaEntity area) {
        return areaService.update(new LambdaUpdateWrapper<AreaEntity>()
                .eq(AreaEntity::getAreaId, area.getAreaId())
                .set(AreaEntity::getAreaName, area.getAreaName())
                .set(AreaEntity::getAreaShow, area.getAreaShow())
                .set(AreaEntity::getAreaNickName, area.getAreaNickName())
                .set(AreaEntity::getAreaParentId, area.getAreaParentId())
                .set(AreaEntity::getAreaPointer, area.getAreaPointer()));
    }

    /**
     * 删除指定区域
     *
     * @param areaId
     * @return
     */
    public boolean deleteAreaById(String areaId) {
        return areaService.removeById(areaId);
    }

    public AreaEntity getAreaById(String areaId) {
        return areaService.getById(areaId);
    }


    /**
     * 设置默认区域
     *
     * @param areaId
     * @return
     */
    public boolean setDefaultArea(String areaId) {
        List<AreaEntity> list = areaService.list();
        Stream<AreaEntity> childList = list.stream().filter(a -> !a.getAreaParentId().equals("0"));
        AreaEntity areaEntity = childList.filter(a -> a.getAreaId().equals(areaId)).findFirst().get();
        if (areaEntity.getAreaDefault()) return true;
        else {
            list.forEach(a -> a.setDefaultArea(a.getAreaId().equals(areaId)));
            return areaService.updateBatchById(list);
        }
    }


    public List<AreaEntity> getAreaList() {
        return areaService.list();
    }


}
